package main.java.top_ip;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.HashMap;
import java.util.Map;

/**
 * TopIpCountBolt
 *
 * @author zhangyimin
 * @version 1.0
 * @date 2018-11-13 下午3:01
 */
public class TopIpCountBolt extends BaseRichBolt {

    private OutputCollector collector;

    private Map<String, Long> result = new HashMap<>();


    @Override
    public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
        this.collector = outputCollector;
    }

    @Override
    public void execute(Tuple tuple) {
        String ip = tuple.getStringByField("ip");

        Long count = tuple.getLongByField("count");


//        Long totalCount = new Long(0);

        if (result.containsKey(ip)){
            result.put(ip,result.get(ip)+count);
        }else{
            result.put(ip,count);
        }


       System.out.println("TOP_IP的结果为:"+result);

        this.collector.emit(new Values(ip,result.get(ip)));

    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {

    }
}
